"""
Flask 应用工厂
"""

from flask import Flask
from flask_cors import CORS
import logging
import os


def create_app():
    """创建并配置 Flask 应用"""
    
    # 创建 Flask 应用
    app = Flask(__name__)
    
    # 根据环境变量加载配置
    env = os.getenv('FLASK_ENV', 'production')
    if env == 'development':
        app.config.from_object('app.config.DevelopmentConfig')
    else:
        app.config.from_object('app.config.ProductionConfig')
    
    # 配置日志
    setup_logging(app)
    
    # 配置 CORS
    setup_cors(app)
    
    # 注册蓝图
    register_blueprints(app)
    
    # 注册错误处理器
    register_error_handlers(app)
    
    return app


def setup_logging(app):
    """配置日志"""
    logging.basicConfig(
        level=logging.INFO if not app.debug else logging.DEBUG,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    app.logger.info('🚀 AI 问答服务启动')
    app.logger.info(f'🌍 环境: {app.config.get("ENV")}')
    app.logger.info(f'🔗 AI API: {app.config.get("AI_API_BASE_URL")}')


def setup_cors(app):
    """配置 CORS"""
    # 允许所有路由的跨域请求
    CORS(app, resources={
        r"/*": {
            "origins": app.config.get('CORS_ORIGINS', ['*']),
            "methods": ["GET", "POST", "OPTIONS"],
            "allow_headers": ["Content-Type", "Authorization", "X-API-Key"]
        }
    })


def register_blueprints(app):
    """注册蓝图"""
    from app.routes import chat_bp, models_bp
    
    # 使用 /ai 前缀，匹配前端请求路径
    app.register_blueprint(chat_bp, url_prefix='/ai')
    app.register_blueprint(models_bp, url_prefix='/ai')


def register_error_handlers(app):
    """注册错误处理器"""
    from flask import jsonify
    
    @app.errorhandler(404)
    def not_found(error):
        return jsonify({'error': '接口不存在'}), 404
    
    @app.errorhandler(500)
    def internal_error(error):
        app.logger.error(f'服务器错误: {str(error)}', exc_info=True)
        return jsonify({'error': '服务器内部错误'}), 500
    
    @app.errorhandler(Exception)
    def handle_exception(error):
        app.logger.error(f'未处理的异常: {str(error)}', exc_info=True)
        return jsonify({'error': '服务器内部错误', 'details': str(error)}), 500
